package com.fangyi.yunmusic.websocket;


import com.alibaba.fastjson.JSON;
import com.fangyi.yunmusic.pojo.ws.CommentNotification;
import com.fangyi.yunmusic.service.notification.CommentNotificationService;
import org.elasticsearch.common.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.SpringConfigurator;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

//@ServerEndpoint(value = "/commentNotification/{userId}")
//@Component
@Deprecated
public class CommentNotificationEndpoint {

    private Logger logger = LoggerFactory.getLogger(CommentNotificationEndpoint.class);

    private static Map<String, Session> livingSessionMap = new ConcurrentHashMap<>();

    @Autowired
    private CommentNotificationService commentNotificationService;

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        livingSessionMap.put(userId, session);
        logger.info(userId + "进入连接");
        // 将用户未读的消息数传给用户
        sendNotReadNum(userId);
    }

    /**
     *  接收客户端信息，告知哪条评论已读了。
     * @param message
     * @param session
     * @param userId
     */
    @OnMessage
    public void onReadComment(String message, Session session, @PathParam("userId") String userId) {
        logger.info(userId + "发送信息" + message);
        CommentNotification cn = JSON.parseObject(message, CommentNotification.class);
        commentNotificationService.remove(cn.getUserId(), cn.getCommentId());
        // 不通知了，客户端自行减1
//        // 更新用户未读消息
//        sendNotReadNum(session, userId);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("发送错误", error);
    }

    @OnClose
    public void onClose(Session session, @PathParam("userId") String userId) {
        livingSessionMap.remove(userId);
        logger.info(userId + "断开连接");
    }

    public void sendMessage(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            logger.error("发送失败", e);
        }
    }

    /**
     * 发送用户未读消息
     * @param userId
     */
    public void sendNotReadNum(String userId) {
        Session session = livingSessionMap.get(userId);
        if (session == null) {
            return ;    // 如果为null，则用户未连接，什么都不做，等用户连接后，自然能从onOpen中获取到消息。
        }
        Long notReadNum = commentNotificationService.getSize(userId);
        CommentNotification commentNotification = new CommentNotification();
        commentNotification.setNotReadCommentNum(notReadNum);
        sendMessage(session, JSON.toJSONString(commentNotification));
    }

    /**
     * 给多个用户发送未读信息
     * @param userIds
     */
    public void sendNotReadNumToMany(List<String> userIds) {
        userIds.forEach(this::sendNotReadNum);
    }

}
